from email.policy import default

from odoo import api, models, fields, _
import logging
from odoo.exceptions import ValidationError
import re

_logger = logging.getLogger(__name__)


class SbSubcontractingApply(models.Model):
    _name = 'sb.subcontracting.apply'
    _inherit = ['portal.mixin', 'mail.thread.main.attachment', 'mail.activity.mixin']

    def _default_name(self):
        return self.env['ir.sequence'].next_by_code('sb.subcontracting.apply')

    @api.depends('line_ids', 'line_ids.workorder_id')
    def _compute_workorder_ids(self):
        if not self.line_ids: return
        workorder_vals = []
        # self.workorder_ids = None
        for line in self.line_ids:
            if not line.workorder_id: continue
            # if not self.partner_id and line.partner_id:
            #     self.partner_id  = line.partner_id.id
            workorder_vals.append((4, line.workorder_id.id))
        self.workorder_ids = workorder_vals

    @api.depends('write_date', 'sb_workflow_state', 'sb_workflow_item_ids')
    def _compute_state(self):
        for rec in self:
            if rec.state == 'cancel':
                rec.state = 'cancel'
            elif rec.sb_workflow_state == 'approval':
                rec.state = 'approval'
            elif rec.sb_workflow_state == 'approve' and rec.purchase_order_ids:
                rec.state = 'generate_purchase'
            elif rec.sb_workflow_state == 'approve' and not rec.purchase_order_ids:
                rec.state = 'approve'
            elif rec.sb_workflow_state == 'fail_to_approve':
                rec.state = 'fail_to_approve'
            else:
                rec.state = 'draft'

    def _compute_purchase_order_count(self):
        for rec in self:
            rec.purchase_order_count = len(rec.purchase_order_ids)

    name = fields.Char(default=_default_name, string='Name', copy=False)

    line_ids = fields.One2many('sb.subcontracting.apply.line', 'apply_id')

    purchase_order_ids = fields.Many2many('purchase.order', string='Purchase Order', copy=False)
    purchase_order_count = fields.Integer(string='Purchase Order Count', compute="_compute_purchase_order_count")
    active = fields.Boolean(default=True)
    state = fields.Selection([
        ('draft', 'Draft'),
        ('approval', 'Approval'),
        ('approve', 'Approve'),
        ('fail_to_approve', 'Fail to Approve'),
        ('generate_purchase', 'Generate Purchase'),
        ('cancel', 'Cancel')
    ], default='draft', string='Status', store=True, compute='_compute_state', tracking=True)
    workorder_ids = fields.Many2many('mrp.workorder', string='Work Orders', compute="_compute_workorder_ids",
                                     store=True)

    sb_workflow_template_id = fields.Many2one(
        'sb.workflow.template', string="Approval Workflow Template",
        domain="[('sb_workflow_template_item_ids', '!=', False), ('workflow_type', '=', 'subcontracting')]"
    )

    sb_workflow_id = fields.Many2one('sb.workflow', string="Current Approval Workflow", copy=False)
    sb_workflow_state = fields.Selection(related="sb_workflow_id.state", readonly=True, string="Approval Status",
                                         store=True)
    sb_workflow_item_ids = fields.One2many(related="sb_workflow_id.sb_workflow_item_ids", string="Approval Items")
    sb_workflow_attachments_ids = fields.One2many(related="sb_workflow_id.sb_workflow_attachments_ids",
                                                  string="Approval Attachments")
    sb_workflow_ids = fields.One2many('sb.workflow', 'subcontracting_id', string="Approval Workflows")
    sb_workflow_ids_sum = fields.Integer(compute="_compute_sb_workflow_ids_sum", store=True)
    sub_date = fields.Datetime(string='Subcontracting Time')
    is_purchase = fields.Boolean(default=False, compute='_compute_is_option')
    is_all_outside = fields.Boolean(default=False, help='包工包料/多工序外发')
    description = fields.Char(string='描述')
    mes_order = fields.Char(string='mes委外单号')

    # 搜索字段
    production_id = fields.Many2one('mrp.production', related='line_ids.production_id', readonly=True)
    product_id = fields.Many2one('product.product', related='line_ids.product_id', readonly=True)

    def _compute_is_option(self):
        if self.state not in ['approve', 'generate_purchase']:
            self.is_purchase = False
        elif self.state == 'approve' and not self.purchase_order_ids:
            self.is_purchase = True
        elif self.state == 'generate_purchase' and self.purchase_order_ids and self.purchase_order_ids.filtered(
                lambda x: x.state != 'cancel'):
            self.is_purchase = False
        elif self.state == 'generate_purchase' and self.purchase_order_ids and not self.purchase_order_ids.filtered(
                lambda x: x.state != 'cancel'):
            self.is_purchase = True
        else:
            self.is_purchase = False

    @api.depends('sb_workflow_ids')
    def _compute_sb_workflow_ids_sum(self):
        for item in self:
            if item.sb_workflow_ids:
                item.sb_workflow_ids_sum = len(item.sb_workflow_ids)
            else:
                item.sb_workflow_ids_sum = 0

    def create_workflow(self):
        if not self.line_ids:
            # 外包工序不能为空
            raise ValidationError(_('Outsourcing process cannot be empty'))

        # 回写工序，外部标志
        for line in self.line_ids:
            qty_wip_pnl = line.workorder_id.qty_wip_pnl - line.workorder_id.subcontracting_received_pnl_qty
            if not qty_wip_pnl:
                qty_wip_pnl = line.production_id.panel_qty
            if qty_wip_pnl <= 0:
                print(line.workorder_id.id, line.production_id.id)
                raise ValidationError(
                    '当前工序可开发数量为0, 已接收数量：{}'.format(line.workorder_id.subcontracting_received_pnl_qty))
            if line.workorder_id.is_subcontracting: continue
            line.workorder_id.is_subcontracting = True
            # 外包申请 占用数量
            # line.workorder_id.occupation_qty = line.qty

        if self.sb_workflow_template_id:
            if len(self.sb_workflow_ids) > 0:
                workflow_sum = len(self.sb_workflow_ids) + 1
            else:
                workflow_sum = 1
            # 创建审批流
            new_wf_id = self.env['sb.workflow'].sudo().create({
                'name': self.name + '- Approval Flow' + '-' + str(workflow_sum),
                'approval_time': fields.Datetime.now(),
                'workflow_type': 'subcontracting',
                'subcontracting_id': self.id,
            })
            self.sb_workflow_id = new_wf_id.id
            # 根据模板生成审批项
            item_audit_levels = []
            for item in self.sb_workflow_template_id.sb_workflow_template_item_ids:
                new_item = self.env['sb.workflow.item'].sudo().create({
                    'name': item.name,
                    'user_group_ids': item.user_group_ids.ids,
                    'audit_level': item.audit_level,
                    'sb_workflow_id': new_wf_id.id,
                    'state': 'wait_forward'
                })
                # 收集生成的审核项的所有层级
                item_audit_levels.append(new_item.audit_level)
            # 去重排序
            item_audit_levels = list(set(item_audit_levels))
            item_audit_levels.sort()
            # 开放最低层级的神匹配
            for n_item in new_wf_id.sb_workflow_item_ids:
                if n_item.audit_level == item_audit_levels[0]:
                    n_item.state = 'approval'
        else:
            raise ValidationError(_('Please select an approval template.'))

    def _get_product_specs(self, product_id):
        uom_panel_width = self.env.ref('pcbmanufact.uom_panel_width')
        uom_panel_length = self.env.ref('pcbmanufact.uom_panel_length')
        uom_ids = product_id.uom_value_ids.mapped('uom_id')
        pnl_width = 0
        pnl_length = 0
        if uom_panel_width in uom_ids and uom_panel_length in uom_ids:
            pnl_width = product_id.uom_value_ids.filtered(lambda x: x.uom_id.id == uom_panel_width.id).uom_value
            pnl_length = product_id.uom_value_ids.filtered(lambda x: x.uom_id.id == uom_panel_length.id).uom_value
        return f"PNL长:{str(pnl_length)};\nPNL宽{str(pnl_width)}"

    @api.model
    def _get_work_remarks(self, workorder_id):
        if not workorder_id:
            return ''
        str_list = []
        cs_area = 0
        ss_area = 0
        for line in workorder_id.operation_id.param_line_ids:
            str_list.append(f'{line.attribute_id.name}:{line.value_id.name}')
            if 'C面金面积' in line.attribute_id.name:
                cs_area = re.findall(r'\d+', line.value_id.name)
            if 'S面金面积' in line.attribute_id.name:
                ss_area = re.findall(r'\d+', line.value_id.name)
        try:
            enig_area = float('.'.join(cs_area)) + float('.'.join(ss_area))
        except Exception as e:
            enig_area = 0
        return ';'.join(str_list), enig_area

    # def create_purchase(self):
    #     self = self.sudo()
    #     if self.sb_workflow_state != 'approve': return
    #     partners = {}
    #     purchase_vals = []
    #     uom_panel = self.env.ref('pcbmanufact.uom_panel')
    #     for line in self.line_ids:
    #         s_service_pricing_method = line.service_product_id.s_service_pricing_method
    #         if line.supplierinfo_id.partner_id and line.qty:
    #             specs = self._get_product_specs(line.product_id)
    #             # remarks, enig_area = self._get_work_remarks(line.workorder_id)
    #             ex_poid = partners.get(line.supplierinfo_id.partner_id.id) or 0
    #             # area_price_unit = line.supplierinfo_id.area_price_unit
    #             # area_pnl_qty = line.supplierinfo_id.area_pnl_qty
    #             # if area_pnl_qty:
    #             #     active_area = round(enig_area / 100 / area_pnl_qty, 5)
    #             #     remarks = remarks + '; (CS+SS)/PNL={}'.format(active_area)
    #
    #             if s_service_pricing_method == 'area':
    #                 price_unit = round(line.area_price_unit * line.area_pnl_qty, 4)
    #             elif s_service_pricing_method == 'panel':
    #                 price_unit = line.supplierinfo_id.panel_price
    #             else:
    #                 raise ValidationError(_('Please first set the pricing method for the service'))
    #
    #             if ex_poid == 0:
    #                 values = {
    #                     'partner_id': line.supplierinfo_id.partner_id.id,
    #                     'subcontracting': True,
    #                     'sb_subcontracting_apply_id': self.id,
    #                     's_service_pricing_method': line.supplierinfo_id.s_service_pricing_method,
    #                     'order_line': [(0, 0, {
    #                         'product_id': line.service_product_id.id,
    #                         'name': line.remark,
    #                         'product_uom': uom_panel.id,
    #                         'display_type': False,
    #                         'date_planned': fields.Datetime.now(),
    #                         'workorder_id': line.workorder_id.id,
    #                         's_subcontracting_product_id': line.product_id.id,
    #                         's_production_id': line.production_id.id,
    #                         's_specs': specs,
    #                         'qty_wip_pcs': line.qty_wip,  # pcs数
    #                         'area_pnl_qty': line.area_pnl_qty,  # 单pnl 有效面积
    #                         'area_price_unit': line.area_price_unit,  # 每平米单价
    #                         's_area': line.area,  # 总平米数
    #                         'price_unit': price_unit,
    #                         'product_qty': line.qty,  # PNL 数
    #                         'taxes_id': [(4, line.supplier_taxes_id.id)] if line.supplier_taxes_id else None,  # PNL 数
    #                         # 'remark': remarks
    #                     })]
    #                 }
    #                 poid = self.env['purchase.order'].create(values)
    #                 # line.done = True
    #                 line.purchase_order_id = poid.id
    #                 partners[line.supplierinfo_id.partner_id.id] = poid.id
    #                 purchase_vals.append((4, poid.id))
    #             else:
    #                 self.env['purchase.order.line'].create({
    #                     'order_id': ex_poid,
    #                     'product_id': line.service_product_id.id,
    #                     'name': line.remark,
    #                     'product_uom': uom_panel.id,  # 默认panel
    #                     'display_type': False,
    #                     'date_planned': fields.Datetime.now(),
    #                     'workorder_id': line.workorder_id.id,
    #                     's_subcontracting_product_id': line.product_id.id,
    #                     's_production_id': line.production_id.id,
    #                     's_specs': specs,
    #                     'qty_wip_pcs': line.qty_wip,  # pcs数
    #                     'area_pnl_qty': line.area_pnl_qty,  # 单pnl 有效面积
    #                     'area_price_unit': line.area_price_unit,  # 每平米单价
    #                     's_area': line.area,  # 总平米数
    #                     'price_unit': round(line.area_price_unit * line.area_pnl_qty, 4),
    #                     'product_qty': line.qty,  # PNL 数
    #                     'taxes_id': [(4, line.supplier_taxes_id.id)] if line.supplier_taxes_id else None,  # PNL 数
    #                     # 'remark': remarks
    #                 })
    #                 # line.done = True
    #                 line.purchase_order_id = ex_poid
    #         else:
    #             raise ValidationError(
    #                 _('{},Please set up outsourcing service products').format(line.supplierinfo_id.partner_id.name))
    #     self.purchase_order_ids = purchase_vals
    #     tree_id = self.env.ref('purchase.purchase_order_kpis_tree').id
    #     form_id = self.env.ref('purchase.purchase_order_form').id
    #     po_ids = [p[1] for p in purchase_vals]
    #     return {
    #         'name': 'Rework',
    #         'type': 'ir.actions.act_window',
    #         'view_type': 'form',
    #         'view_mode': 'form, tree',
    #         'res_model': 'purchase.order',
    #         'domain': [('id', 'in', po_ids)],
    #         'views': [(tree_id, 'tree'), (form_id, 'form')],
    #         'context': {'create': 0},
    #     }

    def select_supplier(self):
        context = dict(self._context)
        context['default_product_id'] = self.line_ids[0].product_id.id
        context['default_service_product_id'] = self.line_ids[0].service_product_id.id
        context['default_apply_id'] = self.id
        context['default_product_ids'] = [(4, p.id) for p in self.line_ids.mapped('product_id')]
        context['default_service_product_ids'] = [(4, p.id) for p in self.line_ids.mapped('service_product_id')]
        if not self.is_all_outside and self.line_ids.filtered(lambda x: not x.service_product_id.s_service_pricing_method):
            raise ValidationError(_('Please first set the pricing method for the service'))
        supplierinfo = self.env['subcontract.product.supplierinfo'].search(
            [('service_product_id', '=', self.line_ids[0].service_product_id.id),
             ('product_id', '=', self.line_ids[0].product_id.id)])
        context['default_supplierinfo_id'] = supplierinfo[0].id if supplierinfo else None
        line_vals = []
        for line in self.line_ids:
            line_vals.append((0, 0, {
                'supplierinfo_id': line.supplierinfo_id.id if line.supplierinfo_id else None,
                'area_price_unit': line.area_price_unit,
                'area_pnl_qty': line.area_pnl_qty,
                'area': line.area,
                'qty': line.qty if not self.is_all_outside else line.done_act_qty,
                'price_unit': line.price_unit,
                'remark': line.remark,
                'service_product_id': line.product_id.id if self.is_all_outside else line.service_product_id.id,
                'product_id': line.product_id.id,
                'supplier_taxes_id': line.product_id.supplier_taxes_id.id,
                'sub_apply_line_id': line.id,
                'area_calculation_method': line.area_calculation_method
            }))
        context['default_line_ids'] = line_vals
        form_id = self.env.ref("sb_subcontracting.supplierinfo_wizard_form_view").id
        return {
            'name': _('Supplier Confirm'),
            'type': 'ir.actions.act_window',
            'res_model': 'supplierinfo.wizard',
            'view_mode': 'form',
            'view_type': 'form',
            'target': 'new',
            'views': [(form_id, 'form')],
            'context': context
        }

    def select_suppliers(self):
        context = dict(self._context)
        if self.filtered(lambda x: x.state == 'generate_purchase') and all([p.state == 'cancel' for p in self.purchase_order_ids]):
            _logger.info('采购单全部取消或删除时候可以再次生成外发PO')
        elif self.filtered(lambda x: x.state !='approve'):
            # 审批通过的外发申请才能下单
            raise ValidationError(_('此操作无法完成，请选择审批通过或未生成外发PO的申请。'))
        line_vals = []
        for rec in self:
            for line in rec.line_ids:
                line_vals.append((0, 0, {
                    'supplierinfo_id': line.supplierinfo_id.id if line.supplierinfo_id else None,
                    'area_price_unit': line.area_price_unit,
                    'area_pnl_qty': line.area_pnl_qty,
                    'area': line.area,
                    'qty': line.qty,
                    'price_unit': line.price_unit,
                    'remark': line.remark,
                    'service_product_id': line.service_product_id.id,
                    'product_id': line.product_id.id,
                    'supplier_taxes_id': line.product_id.supplier_taxes_id.id,
                    'sub_apply_line_id': line.id,
                    'area_calculation_method': line.area_calculation_method
                }))
            context['default_line_ids'] = line_vals
        form_id = self.env.ref("sb_subcontracting.supplierinfo_wizard_form_view").id
        return {
            'name': _('Supplier Confirm'),
            'type': 'ir.actions.act_window',
            'res_model': 'supplierinfo.wizard',
            'view_mode': 'form',
            'view_type': 'form',
            'target': 'new',
            'views': [(form_id, 'form')],
            'context': context
        }

    def action_view_purchases(self):
        return {
            'name': _('Purchase Order'),
            'type': 'ir.actions.act_window',
            'res_model': 'purchase.order',
            'view_mode': 'tree,form',
            'target': 'current',
            'domain': [('id', 'in', self.purchase_order_ids.ids)]}

    def unlink(self):
        if self.state != 'draft':
            raise ValidationError("不能删除当前外发申请")
        return super(SbSubcontractingApply, self).unlink()

    def action_cancel(self):
        self.state = 'cancel'


class SbSubcontractingApplyLine(models.Model):
    _name = 'sb.subcontracting.apply.line'

    apply_id = fields.Many2one('sb.subcontracting.apply')
    production_id = fields.Many2one('mrp.production', string='Production')
    product_id = fields.Many2one('product.product', string='Product')
    workorder_id = fields.Many2one('mrp.workorder', string='Work Order')
    # 剩余数量
    qty_remaining = fields.Float('Remaining Quantity', digits='Product Unit of Measure')
    qty_wip_pnl = fields.Float('Work In Process (PNL)', digits='Product Unit of Measure')
    qty_wip = fields.Float('Work In Process', digits='Product Unit of Measure')
    # 实际处理数量
    done_act_qty = fields.Float('Ordered Quantity(PCS)', digits='Product Unit of Measure')
    # 本次下单数
    qty = fields.Float('Quantity for This Order', digits='Product Unit of Measure')
    # done = fields.Boolean("Processed")
    # 面积(m^2)
    area = fields.Char(string='Area', copy=False)
    # 供应商价格表，(客户)
    supplierinfo_id = fields.Many2one('subcontract.product.supplierinfo', string='Supplier Price List')
    # 工作中心-服务名称
    service_product_id = fields.Many2one('product.product')
    create_date = fields.Datetime(default=lambda self: fields.Datetime.now())
    purchase_order_id = fields.Many2one('purchase.order', copy=False)
    subcontracting_received_qty = fields.Integer(string='Subcontracting Received Qty')
    subcontracting_received_pnl_qty = fields.Integer(string='Subcontracting Received Pnl Qty')
    remark = fields.Text(string='描述')
    area_pnl_qty = fields.Float(string='Active PANEL/M²', digits="Product Unit of Measure")
    supplier_taxes_id = fields.Many2one(comodel_name='account.tax', string="Taxes")
    area_price_unit = fields.Float('Area Price Unit', digits="Product Unit of Measure")
    price_unit = fields.Float('Price Unit', digits="Product Unit of Measure")
    s_service_pricing_method = fields.Selection([('panel', 'Panel'), ('area', 'Area')],
                                                string='Subcontracting Pricing Method')
    partner_id = fields.Many2one('res.partner', string='supplier')
    area_calculation_method = fields.Selection([
        ('pnl', 'PNL'),
        ('set', 'SET')
    ], string='Area calculation method', default='pnl')
    start_workorder_id = fields.Many2one('mrp.workorder', string='开始工单')
    stop_workorder_id = fields.Many2one('mrp.workorder', string='结束工单')
    # is_all_outside = fields.Boolean(default=False, help='包工包料/多工序外发')

    @api.onchange('supplierinfo_id')
    def onchange_area_price_unit(self):
        if self.supplierinfo_id and self.s_service_pricing_method == 'panel':
            self.price_unit = self.supplierinfo_id.panel_price
        elif self.supplierinfo_id and self.s_service_pricing_method == 'area':
            self.area_price_unit = self.supplierinfo_id.area_price_unit
            self.price_unit = round(self.area_price_unit * self.area_pnl_qty, 4)
        else:
            self.area_price_unit = 0
            self.price_unit = 0

    def _get_panel_width_height(self, product_id):
        uom_values = {x.uom_id.name: x.uom_value for x in product_id.uom_value_ids}
        panel_height = uom_values.get('Panel长', 0)
        panel_width = uom_values.get('Panel宽', 0)
        panel_qty = uom_values.get('PANEL', 0)
        return panel_height, panel_width, panel_qty

    def get_unit_number(self, product_id):
        uom_panel_width = self.env.ref('pcbmanufact.uom_panel_width')
        uom_panel_length = self.env.ref('pcbmanufact.uom_panel_length')
        uom_ids = product_id.uom_value_ids.mapped('uom_id')
        pnl_width = 0
        pnl_length = 0
        if uom_panel_width in uom_ids and uom_panel_length in uom_ids:
            pnl_width = product_id.uom_value_ids.filtered(lambda x: x.uom_id.id == uom_panel_width.id).uom_value
            pnl_length = product_id.uom_value_ids.filtered(lambda x: x.uom_id.id == uom_panel_length.id).uom_value
        return pnl_length, pnl_width

    def _compute_unit_area(self, product_id, compute_type='pnl'):
        uom_values = {x.uom_id.code: x.uom_value for x in product_id.uom_value_ids}
        if compute_type == 'set':
            w = uom_values.get('SETW', 1)
            h = uom_values.get('SETL', 1)
            p = uom_values.get('PANEL', 1)
            s = uom_values.get('SET', 1)
            unit_area = w * h / 1000000 * (p / s)
        else:
            w = uom_values.get('PNLW', 1)
            h = uom_values.get('PNLL', 1)
            unit_area = w * h / 1000000
        return round(unit_area, 3)

    @api.onchange('workorder_id', 'area_calculation_method', 'qty')
    def onchange_qty(self):
        if not self.workorder_id:
            return

        sub_contract_product_tmpl_id = self.workorder_id.workcenter_id.sub_contract_product_tmpl_id
        if not sub_contract_product_tmpl_id:
            # 请先到工作中配置外发服务名称
            raise ValidationError(_('Please configure the outsourcing service name in the work first.'))
        service_product_id = self.env['product.product'].sudo().search(
            [('product_tmpl_id', '=', sub_contract_product_tmpl_id.id)])

        if self.area_calculation_method == 'set':
            qty_wip_pnl = self.workorder_id.qty_wip_set
            if not qty_wip_pnl:
                qty_wip_pnl = sum(self.production_id.workorder_ids.mapped('qty_wip_set'))

        else:
            # 原始生产数量 - (外包接收的数量/ 比例)
            qty_wip_pnl = self.workorder_id.qty_wip_pnl - self.workorder_id.subcontracting_received_pnl_qty
            if not qty_wip_pnl:
                qty_wip_pnl = sum(self.production_id.workorder_ids.mapped('qty_wip_pnl'))

        # 计算单 PNL / SET 的面积
        area_pnl_qty = self._compute_unit_area(self.workorder_id.product_id, self.area_calculation_method)
        area = qty_wip_pnl * area_pnl_qty

        remarks, enig_area = self._get_work_remarks(self.workorder_id)
        if area_pnl_qty:
            active_area = round(enig_area / 100 / area_pnl_qty, 5)
            remarks = remarks + '; (CS+SS)/PNL={}'.format(active_area)

        self.write({
            'remark': remarks,
            'area_pnl_qty': area_pnl_qty,
            'area': round(area, 3),
            'done_act_qty': self.workorder_id.done_act_qty,  # 实际处理数量
            'qty_remaining': self.workorder_id.qty_remaining,  # 总数量(PCS)
            'qty_wip': self.workorder_id.qty_wip,
            'qty_wip_pnl': qty_wip_pnl,
            'qty': qty_wip_pnl,                                # 本次下单数
            'service_product_id': service_product_id.id,
            's_service_pricing_method': service_product_id.s_service_pricing_method,
            'subcontracting_received_qty': self.workorder_id.subcontracting_received_qty,
            'subcontracting_received_pnl_qty': self.workorder_id.subcontracting_received_pnl_qty,
        })

    @api.onchange('production_id')
    def onchange_product_id(self):
        if not self.production_id:
            self.product_id = None
        else:
            ids = self.production_id._get_sources()
            parent_ids = [rec for rec in ids]
            if not parent_ids:
                origin = self.production_id
            else:
                production_id = parent_ids[0]
                while parent_ids:
                    production_id = parent_ids.pop()
                    ids = production_id._get_sources()
                    parent_ids = [rec for rec in ids]
                origin = production_id
            self.product_id = origin.product_id.id

    def _get_work_remarks(self, workorder_id):
        if not workorder_id:
            return ''
        str_list = []
        cs_area = 0
        ss_area = 0
        for line in workorder_id.operation_id.param_line_ids:
            str_list.append(f'{line.attribute_id.name}:{line.value_id.name}')
            if 'C面金面积' in line.attribute_id.name:
                cs_area = re.findall(r'\d+', line.value_id.name or '')
            if 'S面金面积' in line.attribute_id.name:
                ss_area = re.findall(r'\d+', line.value_id.name or '')
        try:
            enig_area = float('.'.join(cs_area)) + float('.'.join(ss_area))
        except Exception as e:
            enig_area = 0
        return ';'.join(str_list), enig_area

    # @api.onchange('qty')
    # def onchange_area(self):
    #     pnl_length, panel_width = self.get_unit_number(self.workorder_id.product_id)
    #     if self.qty:
    #         qty_wip_pnl = self.qty
    #     else:
    #         qty_wip_pnl = self.qty_wip_pnl
    #     area = qty_wip_pnl * pnl_length * panel_width / 1000000
    #     self.area = round(area, 3)

    def create_supplierinfo(self):
        context = dict(self._context)
        context['default_product_id'] = self.product_id.id
        context['default_area_pnl_qty'] = self.area_pnl_qty
        context['default_service_product_id'] = self.service_product_id.id
        form_id = self.env.ref("sb_subcontracting.subcontract_product_supplierinfo_form_view").id

        return {
            'name': 'Create Supplierinfo',
            'type': 'ir.actions.act_window',
            'view_type': 'form',
            'view_mode': 'form',
            'target': 'new',
            'res_model': 'subcontract.product.supplierinfo',
            'views': [(form_id, 'form')],
            'context': context,
        }

